package com.henry.base.spring;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassPathXmlApplicationContext implements BeanFactory {
    private String xmlPath;
    private Map<String, Object> beans = new HashMap<>();

    //构造函数，完成xml文件的解析
    public ClassPathXmlApplicationContext(String xmlPath) throws DocumentException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        //1.读取xml配置文件
        SAXReader reader = new SAXReader();
        Document document = reader.read(this.getClass().getClassLoader().getResource(xmlPath));
        Element root = document.getRootElement();

        //获取bean元素集合
        List<Element> elements = root.elements();
        Object obj = null;
        for (Element element : elements) {
            //获取到每个bean配置，获得class地址
            String beanId = element.attributeValue("id");
            String beanClassPath = element.attributeValue("class");
            Class<?> clz = Class.forName(beanClassPath);
            obj = clz.newInstance();
            //拿到成员属性
            List<Element> attrs = element.elements();
            for (Element attr : attrs) {
                String name = attr.attributeValue("name");
                String value = attr.attributeValue("value");
                //使用反射为私有属性赋值
                Field field = clz.getDeclaredField(name);
                field.setAccessible(true);
                field.set(obj,value);
            }
            beans.put(beanId, obj);
        }
    }

    @Override
    public Object getBean(String name) {
        return beans.get(name);
    }
}
